using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;

namespace CodePlex.Resourceful
{
    public static class SilverlightCompat11
    {
        public static byte[] ToHMACSHA1(Encoding encoding, string key, string input)
        {
            return SilverlightSHA1.ToHMACSHA1(encoding, key, input);
        }

        public static string ReadString(XmlReader reader)
        {
            if (reader.ReadState != ReadState.Interactive)
            {
                return string.Empty;
            }
            reader.MoveToElement();
            if (reader.NodeType == XmlNodeType.Element)
            {
                if (reader.IsEmptyElement)
                {
                    return string.Empty;
                }
                if (!reader.Read())
                {
                    throw CodePlexException.Format("Invalid xml operation.");
                }
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    return string.Empty;
                }
            }

            StringBuilder rt = new StringBuilder();
            while (0L != (0x6018 & (((int)1) << ((int)reader.NodeType))))
            {
                rt.Append(reader.Value);
                if (!reader.Read())
                {
                    return rt.ToString();
                }
            }
            return rt.ToString();
        }


        // from http://www.1perlscriptstreet.com/URLSEO/vb/scripts/ShowCode!asp/txtCodeId!4147/lngWid!2/anyname.htm

        //**************************************
        //     
        // Name: SHA1.java
        // Description:Generate a secured hash S
        //     tring from an input of String data, or S
        //     tring data and String key. This implemen
        //     tation includes the java for the server 
        //     side and JavaScript for the client side.
        //     The SHA1.java is a Java implementation o
        //     f the JavaScript library 'sha1.js' that 
        //     is an implementation of the Secure Hash 
        //     Algorithm, SHA-1, as defined in FIPS PUB
        //     180-1. The Java code completes the JavaS
        //     cript library code for a client / server
        //     usage where the client can use the JavaS
        //     cript code to encrypt a password by pass
        //     ing it into one of the JavaScript librar
        //     y functions. The server may then use the
        //     Java code to compare the encrypted strin
        //     g to any of the availabe passwords. It c
        //     an even use a key, a string generated by
        //     the server (ip address or system time) t
        //     o use as an encryption base for the pass
        //     word. Together, the JavaScript code and 
        //     the java code provide a basic authentica
        //     tion mechanism that is of a low level se
        //     curity. Using ssl (https) makes it high 
        //     level secured. Using ssl and this code, 
        //     makes it super secured.
        // sha1.js version 2.1 is a Copyright of Paul Johnston 2000 - 2002. SHA1.java is a copyright of T.N.Silverman 2004. Distributed under the BSD License. 
        // NOTICE!!! The colored lines bellow where inserted automatically by planet source code to the html I uploaded. It was done for security reasons and replaced my original code. However, It is wrong and you should insert the line <SCRIPT LANGUAGE=JAVASCRIPT>" right after the opening "<HEAD>" tag istead of the second colored line. Change the '..' to 'ip' and delete the first colored line. Leave the third one there.
        // By: T.N.Silverman (tnsilver)
        //
        // Inputs:String "data" and / or String 
        //     "key".
        //
        // Returns:java.lang.String SHA1 (either
        //     plain-text, hexdecimal or base64 encodin
        //     g).
        //
        // Assumes:SHA1.java is an Abstract Clas
        //     s. You can not make new instances of it.
        //     You need to call it from another class b
        //     y writing something like: java.lang.Stri
        //     ng sha1 = SHA1.hex_hmac_sha1("key", "dat
        //     a"); If you print the result (System.out
        //     .println(sha1);) you should always have 
        //     this: 104152c5bfdca07bc633eebd46199f0255
        //     c9f49d To test the work of the Java, add
        //     a main method to SHA1.java and call the 
        //     doTest() method.
        //
        // Side Effects:Make sure the instance v
        //     ariables of the java code are identical 
        //     to the sha1.js global variables (there a
        //     re 3 in each). Plus - I have no idea how
        //     this code acts when used with funny lang
        //     uages written from right to left, top to
        //     bottom or use non ascii characters (char
        //     acters > 255) and strange charsets. T
        //     ry and tell me.
        //
        //This code is copyrighted and has// limited warranties.Please see http://
        //     www.1PerlScriptStreet.com/vb/scripts/Sho
        //     wCode.asp?txtCodeId=4147&lngWId=2//for details.//**************************************
        //     

        /*Apologies for the terrible identation - it's due to planet source codes handling of this code and printing it here. Nothing I can do.*/


        private static class SilverlightSHA1
        {
            private static readonly bool hexcase = false;/* hex output format. false - lowercase; true - uppercase */
            private static readonly String b64pad = "="; /* base-64 pad character. "=" for strict RFC compliance */
            private static readonly int chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
            /**
            * this is one of the functions you'll usually want to call
            * It take a string arguments and returns either hex or base-64 encoded strings
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param key java.lang.String
            * @param data java.lang.String
            */


            private static String b64_hmac_sha1(String key, String data)
            {
                return binb2b64(core_hmac_sha1(key, data));
            }

            /**
            * this is one of the functions you'll usually want to call
            * It take a string argument and returns either hex or base-64 encoded strings
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param s java.lang.String
            */


            private static String b64_sha1(String s)
            {
                s = (s == null) ? "" : s;
                return binb2b64(core_sha1(str2binb(s), s.Length * chrsz));
            }

            /**
            * Convert an array of big-endian words to a base-64 string
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param binarray int[]
            */


            private static String binb2b64(int[] binarray)
            {
                String tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
                String str = "";
                binarray = strechBinArray(binarray, binarray.Length * 4);


                for (int i = 0; i < binarray.Length * 4; i += 3)
                {
                    int triplet =
                    (((binarray[i >> 2] >> 8 * (3 - i % 4)) & 0xFF) << 16)
                    | (((binarray[i + 1 >> 2] >> 8 * (3 - (i + 1) % 4)) & 0xFF) << 8)
                    | ((binarray[i + 2 >> 2] >> 8 * (3 - (i + 2) % 4)) & 0xFF);


                    for (int j = 0; j < 4; j++)
                    {
                        if (i * 8 + j * 6 > binarray.Length * 32)
                            str += b64pad;
                        else
                            str += tab[(triplet >> 6 * (3 - j)) & 0x3F];
                    }

                }

                return cleanB64Str(str);
            }

            /**
            * Convert an array of big-endian words to a hex string.
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param binarray int[]
            */


            private static String binb2hex(int[] binarray)
            {
                String hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
                String str = "";


                for (int i = 0; i < binarray.Length * 4; i++)
                {
                    char a = (char)hex_tab[(binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF];
                    char b = (char)hex_tab[(binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF];
                    str += (a.ToString() + b.ToString());
                }

                return str;
            }

            /**
            * Convert an array of big-endian words to a string
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param bin int[]
            */


            private static String binb2str(int[] bin)
            {
                String str = "";
                int mask = (1 << chrsz) - 1;
                for (int i = 0; i < bin.Length * 32; i += chrsz)
                    str += (char)((UnsignedRightShift(bin[i >> 5], (24 - i % 32))) & mask);
                return str;
            }

            /**
            * Bitwise rotate a 32-bit number to the left.
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int
            * @param num int
            * @param cnt int
            */


            private static int bit_rol(int num, int cnt)
            {
                return (num << cnt) | (UnsignedRightShift(num, (32 - cnt)));
            }

            /**
            * Cleans a base64 String from all the trailing 'A' or other
            * characters put there by binb2b64 that made the bin array
            * 4 times larger than it originally was.
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param str java.lang.String
            */


            private static String cleanB64Str(String str)
            {
                str = (str == null) ? "" : str;
                int len = str.Length;
                if (len <= 1)
                    return str;
                char trailChar = str[len - 1];
                String trailStr = "";
                for (int i = len - 1; i >= 0 && str[i] == trailChar; i--)
                    trailStr += str[i];
                return str.Substring(0, str.IndexOf(trailStr));
            }

            /**
            * Makes an int array of a length less than 16 an array of length 16 with all previous
            * cells at their previous indexes.
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int[]
            * @param str java.lang.String
            */


            private static int[] complete216(int[] oldbin)
            {
                if (oldbin.Length >= 16)
                    return oldbin;
                int[] newbin = new int[16 - oldbin.Length];
                for (int i = 0; i < newbin.Length; newbin[i] = 0, i++) ;
                return concat(oldbin, newbin);
            }

            /**
            * Joins two int arrays and return one that contains all the previous values.
            * this corresponds to the concat method of the JavaScript Array object.
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0 
            * @return int[]
            * @param str java.lang.String
            */


            private static int[] concat(int[] oldbin, int[] newbin)
            {
                int[] retval = new int[oldbin.Length + newbin.Length];


                for (int i = 0; i < (oldbin.Length + newbin.Length); i++)
                {
                    if (i < oldbin.Length)
                        retval[i] = oldbin[i];
                    else
                        retval[i] = newbin[i - oldbin.Length];
                }

                return retval;
            }

            /**
            * Calculate the HMAC-SHA1 of a key and some data
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int
            * @param x java.lang.String[]
            * @param len int
            */


            private static int[] core_hmac_sha1(String key, String data)
            {
                key = (key == null) ? "" : key;
                data = (data == null) ? "" : data;
                int[] bkey = complete216(str2binb(key));
                if (bkey.Length > 16)
                    bkey = core_sha1(bkey, key.Length * chrsz);
                int[] ipad = new int[16];
                int[] opad = new int[16];
                for (int i = 0; i < 16; ipad[i] = 0, opad[i] = 0, i++) ;


                for (int i = 0; i < 16; i++)
                {
                    ipad[i] = bkey[i] ^ 0x36363636;
                    opad[i] = bkey[i] ^ 0x5C5C5C5C;
                }

                int[] hash =
                core_sha1(concat(ipad, str2binb(data)), 512 + data.Length * chrsz);
                return core_sha1(concat(opad, hash), 512 + 160);
            }

            /**
            * Calculate the SHA-1 of an array of big-endian words, and a bit length
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int
            * @param x java.lang.String[]
            * @param len int
            */


            private static int[] core_sha1(int[] x, int len)
            {
                /* append padding */
                int size = (len >> 5);
                x = strechBinArray(x, size);
                x[len >> 5] |= 0x80 << (24 - len % 32);
                size = ((len + 64 >> 9) << 4) + 15;
                x = strechBinArray(x, size);
                x[((len + 64 >> 9) << 4) + 15] = len;
                int[] w = new int[80];
                int a = 1732584193;
                int b = -271733879;
                int c = -1732584194;
                int d = 271733878;
                int e = -1009589776;


                for (int i = 0; i < x.Length; i += 16)
                {
                    int olda = a;
                    int oldb = b;
                    int oldc = c;
                    int oldd = d;
                    int olde = e;


                    for (int j = 0; j < 80; j++)
                    {
                        if (j < 16)
                            w[j] = x[i + j];
                        else
                            w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                        int t =
                        safe_add(
                        safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
                        safe_add(safe_add(e, w[j]), sha1_kt(j)));
                        e = d;
                        d = c;
                        c = rol(b, 30);
                        b = a;
                        a = t;
                    }

                    a = safe_add(a, olda);
                    b = safe_add(b, oldb);
                    c = safe_add(c, oldc);
                    d = safe_add(d, oldd);
                    e = safe_add(e, olde);
                }

                int[] retval = new int[5];
                retval[0] = a;
                retval[1] = b;
                retval[2] = c;
                retval[3] = d;
                retval[4] = e;
                return retval;
            }

            /**
            * Just a test function to output the results of the 6 working funcions to the standard out.
            * The two Strings used as parameters are null. Feel free to test with different values.
            * Creation date:(3/27/20046:05:10PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            */


            private static void doTest()
            {
                String key = "key";
                String data = "data";
                Console.WriteLine("hex_sha1(" + data + ")=" + hex_sha1(data));
                Console.WriteLine("b64_sha1(" + data + ")=" + b64_sha1(data));
                Console.WriteLine("str_sha1(" + data + ")=" + str_sha1(data));
                Console.WriteLine("hex_hmac_sha1(" + key + "," + data + ")=" + hex_hmac_sha1(key, data));
                Console.WriteLine("b64_hmac_sha1(" + key + "," + data + ")=" + b64_hmac_sha1(key, data));
                Console.WriteLine("str_hmac_sha1(" + key + "," + data + ")=" + str_hmac_sha1(key, data));
            }




            public static byte[] ToHMACSHA1(Encoding encoding, string key, string input)
            {
                string rt = hex_hmac_sha1(key, input);
                return Utils.FromBase16(rt);

            }

            /**
            * this is one of the functions you'll usually want to call
            * It take a string arguments and returns either hex or base-64 encoded strings
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param key java.lang.String
            * @param data java.lang.String
            */




            private static String hex_hmac_sha1(String key, String data)
            {
                return binb2hex(core_hmac_sha1(key, data));
            }

            /**
            * this is one of the functions you'll usually want to call
            * It take a string argument and returns either hex or base-64 encoded strings
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param s java.lang.String
            */


            private static String hex_sha1(String s)
            {
                s = (s == null) ? "" : s;
                return binb2hex(core_sha1(str2binb(s), s.Length * chrsz));
            }

            /**
            * Bitwise rotate a 32-bit number to the left. * Creation date: (3/26/2004 1:05:01 PM)
            * Creation date: (3/27/2004 6:05:10 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int
            * @param num int
            * @param cnt int
            */


            private static int UnsignedRightShift(int lhs, int rhs)
            {
                return (int)((uint)lhs >> rhs);
            }


            private static int rol(int num, int cnt)
            {



                return (num << cnt) | (UnsignedRightShift(num, (32 - cnt)));
            }

            /**
            * Add ints, wrapping at 2^32. this uses 16-bit operations internally
            * to work around bugs in some JS interpreters. The original function
            * is part of the sha1.js library. It's here for compatibility.
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int
            * @param num int
            * @param cnt int
            */


            private static int safe_add(int x, int y)
            {
                int lsw = (int)(x & 0xFFFF) + (int)(y & 0xFFFF);
                int msw = (x >> 16) + (y >> 16) + (lsw >> 16);
                return (msw << 16) | (lsw & 0xFFFF);
            }

            /**
            * Perform the appropriate triplet combination function for the current
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int
            * @param t int
            * @param b int
            * @param c int
            * @param d int
            */


            private static int sha1_ft(int t, int b, int c, int d)
            {
                if (t < 20)
                    return (b & c) | ((~b) & d);
                if (t < 40)
                    return b ^ c ^ d;
                if (t < 60)
                    return (b & c) | (b & d) | (c & d);
                return b ^ c ^ d;
            }

            /**
            * Determine the appropriate additive constant for the current iteration
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int
            * @param t int
            */


            private static int sha1_kt(int t)
            {
                return (t < 20)
                ? 1518500249
                : (t < 40)
                ? 1859775393
                : (t < 60)
                ? -1894007588
                : -899497514;
            }

            /**
            * this is a boolean returnig test function that exists in the sha1.js library.
            * if it returns 'false' something is wrong. 
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param s java.lang.String
            */


            private static bool sha1_vm_test()
            {
                return hexcase ? hex_sha1("abc").Equals("A9993E364706816ABA3E25717850C26C9CD0D89D") : hex_sha1("abc").Equals("a9993e364706816aba3e25717850c26c9cd0d89d");
            }

            /**
            * this is one of the functions you'll usually want to call
            * It take a string arguments and returns either hex or base-64 encoded strings
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param key java.lang.String
            * @param data java.lang.String
            */


            private static String str_hmac_sha1(String key, String data)
            {
                return binb2str(core_hmac_sha1(key, data));
            }

            /**
            * this is one of the functions you'll usually want to call
            * It take a string argument and returns either hex or base-64 encoded strings
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return java.lang.String
            * @param s java.lang.String
            */


            private static String str_sha1(String s)
            {
                s = (s == null) ? "" : s;
                return binb2str(core_sha1(str2binb(s), s.Length * chrsz));
            }

            /**
            * Convert an 8-bit or 16-bit string to an array of big-endian words
            * in 8-bit function, characters >255 have their hi-byte silently ignored.
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int[]
            * @param str java.lang.String
            */


            private static int[] str2binb(String str)
            {
                str = (str == null) ? "" : str;
                int[] tmp = new int[str.Length * chrsz];
                int mask = (1 << chrsz) - 1;
                for (int i = 0; i < str.Length * chrsz; i += chrsz)
                    tmp[i >> 5] |= ((int)(str[i / chrsz]) & mask) << (24 - i % 32);
                int len = 0;
                for (int i = 0; i < tmp.Length && tmp[i] != 0; i++, len++) ;
                int[] bin = new int[len];
                for (int i = 0; i < len; i++)
                    bin[i] = tmp[i];
                return bin;
            }

            /**
            * increase an int array to a desired sized + 1 while keeping the old values.
            * Creation date: (3/26/2004 1:05:01 PM)
            * @author T.N.Silverman
            * @version 1.0.0
            * @return int[]
            * @param str java.lang.String
            */


            private static int[] strechBinArray(int[] oldbin, int size)
            {
                int currlen = oldbin.Length;
                if (currlen >= size + 1)
                    return oldbin;
                int[] newbin = new int[size + 1];
                for (int i = 0; i < size; newbin[i] = 0, i++) ;
                for (int i = 0; i < currlen; i++)
                    newbin[i] = oldbin[i];
                return newbin;
            }

        }
    }

}

